package com.zg.nacos.manager;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/6/27 19:58
 */

// 文件: InstanceManager.java (新建)

import com.zg.nacos.domain.bo.InstanceInfo;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
public class InstanceManager {
    // 存储实例信息 key: namespace@serviceCode@ip:port
    private final Map<String, InstanceInfo> instances = new ConcurrentHashMap<>();
    
    // 按服务分组存储 [namespace@serviceCode -> 实例列表]
    private final Map<String, List<InstanceInfo>> serviceInstances = new ConcurrentHashMap<>();

    public void addInstance(InstanceInfo info) {
        String instanceKey = genKey(info);
        String serviceKey = genServiceKey(info);

        instances.put(instanceKey, info);

        serviceInstances.computeIfAbsent(serviceKey, k -> new CopyOnWriteArrayList<>())
                .add(info);
    }

    public InstanceInfo getInstance(String namespace, String serviceCode, String ip, int port) {
        return instances.get(genKey(namespace, serviceCode, ip, port));
    }

    public List<InstanceInfo> getServiceInstances(String namespace, String serviceCode) {
        return serviceInstances.getOrDefault(genServiceKey(namespace, serviceCode),
                Collections.emptyList());
    }

    public void removeInstance(String namespace, String serviceCode, String ip, int port) {
        String instanceKey = genKey(namespace, serviceCode, ip, port);
        String serviceKey = genServiceKey(namespace, serviceCode);

        InstanceInfo removed = instances.remove(instanceKey);
        if (removed != null) {
            List<InstanceInfo> list = serviceInstances.get(serviceKey);
            if (list != null) {
                list.removeIf(inst -> genKey(inst).equals(instanceKey));

                // 清理空列表
                if (list.isEmpty()) {
                    serviceInstances.remove(serviceKey);
                }
            }
        }
    }

    private String genServiceKey(InstanceInfo info) {
        return info.getNamespace() + "@" + info.getServiceCode();
    }

    private String genServiceKey(String namespace, String serviceCode) {
        return namespace + "@" + serviceCode;
    }



    public Map<String, InstanceInfo> getAllInstances() {
        return instances;
    }

    private String genKey(InstanceInfo info) {
        return info.getNamespace() + "@" + info.getServiceCode() + "@"
                + info.getIp() + ":" + info.getPort();
    }

    private String genKey(String namespace, String serviceCode, String ip, int port) {
        return namespace + "@" + serviceCode + "@" + ip + ":" + port;
    }
}